//
//  BanBu_FriendListController.m
//  BanBu
//
//  Created by Wang Xj on 13-8-22.
//
//

#import "BanBu_FriendListController.h"
#import "BanBu_FriendListCell.h"
#import "AppCommunicationManager.h"
#import "AppDataManager.h"
#import "BanBu_NavButton.h"
#import "CJSONSerializer.h"
#import "BanBu_ChatViewController.h"

@interface BanBu_FriendListController ()

@end

@implementation BanBu_FriendListController

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.searchBl = NO;
    MyAppDataManager.friendController = self;
    
    self.title = NSLocalizedString(@"choosePerson", nil);

    self.friendListArray = [NSMutableArray arrayWithCapacity:30];
    self.chooseDic = [NSMutableDictionary dictionaryWithCapacity:20];
    self.pnameDic = [NSMutableDictionary dictionaryWithCapacity:30];
    
    self.tableView.backgroundColor = [UIColor colorWithRed:255.0/255 green:250.0/255 blue:240.0/255 alpha:1.0];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.allowsSelectionDuringEditing = YES;
    
    CGFloat btnLen1 = [NSLocalizedString(@"choose", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
    self.chooseButton = [[[BanBu_NavButton alloc] initWithButtonType:UIButtonCreatTypeNormal] autorelease];
    self.chooseButton.position = ButtonPositionRight;
    self.chooseButton.frame=CGRectMake(0, 0, btnLen1+20, 30);
    self.chooseButton.tag = 101;
    [self.chooseButton addTarget:self action:@selector(setEditing:animated:) forControlEvents:UIControlEventTouchUpInside];
    [self.chooseButton setTitleEdgeInsets:UIEdgeInsetsMake(3, 2, 2, 2)];
    [self.chooseButton setTitle:NSLocalizedString(@"choose", nil) forState:UIControlStateNormal];
    self.chooseButton.titleLabel.font = [UIFont systemFontOfSize:14];
    
    UIBarButtonItem *delItem = [[[UIBarButtonItem alloc] initWithCustomView:self.chooseButton] autorelease];
    self.navigationItem.rightBarButtonItem = delItem;
    
    BanBu_ImageView *img = [[[BanBu_ImageView alloc] initWithBackGroundImageType:UIImageViewCreatTypeTable] autorelease];
    self.tableView.backgroundView = img;
    
    NSString * fileName = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"friendList_Transmit"];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:fileName])
    {
        //获取好友列表
        NSDictionary * friendListDic = [NSKeyedUnarchiver unarchiveObjectWithFile:fileName];
        
        NSDate * updateDate = [friendListDic valueForKey:@"updateDate"];
        self.friendListArray = [friendListDic valueForKey:FriendShip];
        
        [self transmitArrToDic:self.friendListArray];
        
        if (fabs([updateDate timeIntervalSinceNow])>86400)
        {
            //获取好友列表
            [AppComManager getBanBuData:BanBu_GetFriendList_transmit par:nil delegate:MyAppDataManager];
        }
    }
    else
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"isDownloading", nil) activityAnimated:YES];
        //获取好友列表
        [AppComManager getBanBuData:BanBu_GetFriendList_transmit par:nil delegate:MyAppDataManager];
    }
    
    //加载搜索框
    self.searchView = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0, 0.0, self.view.bounds.size.width, 40)] autorelease];
    self.searchView.delegate = self;
    
    //2
    UISearchDisplayController * searchDisPlay = [[UISearchDisplayController alloc]initWithSearchBar:self.searchView contentsController:self];
    searchDisPlay.delegate = self;
    searchDisPlay.searchResultsDelegate = self;
    searchDisPlay.searchResultsDataSource = self;
    
    self.tableView.tableHeaderView = self.searchView;
    
    [self setEditing:YES animated:YES];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dismissTKLoading
{
    [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"sendS", nil) activityAnimated:NO duration:1.2f];
    if(_chatController)
    {
        [self.navigationController popToViewController:_chatController animated:YES];
    }
}

//将姓名转存到姓名资料字典中
-(void)transmitArrToDic:(NSArray *)infoArray
{
    for (NSDictionary * dic in infoArray)
    {
        [self.pnameDic setValue:dic forKey:[dic valueForKey:KeyPname]];
    }
}

//修改tableView可编辑状态
- (void)setEditing:(BOOL)editting animated:(BOOL)animated
{
	[super setEditing:!self.editing animated:YES];
    
    if(self.editing)
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"sendReply", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        self.chooseButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [self.chooseButton setTitle:NSLocalizedString(@"sendReply", nil) forState:UIControlStateNormal];
    }
    else
    {
        //为了使用多语言环境，改变文本显示时，要调整按钮长度
        CGFloat btnLen1 = [NSLocalizedString(@"choose", nil) sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(150, 30)].width;
        self.chooseButton.frame=CGRectMake(320-btnLen1-20-5, 7, btnLen1+20, 30);
        
        [self.chooseButton setTitle:NSLocalizedString(@"choose", nil) forState:UIControlStateNormal];
    }
    
    if(self.chooseDic.count)
    {
        [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"sendingNotice", nil) activityAnimated:YES];
        
        dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
        dispatch_async(queue, ^{
            
            if (self.isVisitingCard)
            {
                NSDictionary *sendDic = [NSDictionary dictionaryWithObjectsAndKeys:self.visitCardInfoDic,KeyContent,ChatCellTypeSpecialText,KeyType,@"visitCard",KeyShowFrom,nil];
                                
                [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
            }
            else
            {
                //在数据库中保存转发的聊天记录
                //useridAndChatIDDic：userid与chatid一一对应
                NSDictionary * useridAndChatIDDic = [MyAppDataManager saveTransmitMsg:self.msgDic andUseruserInfoDic:self.chooseDic];//[MyAppDataManager saveTransmitMsg:self.msgDic andUserIDList:self.chooseDic];
                
                NSArray *mapArr = typeArrDefine;
                
                NSDictionary *saysDic = [NSDictionary dictionaryWithObjectsAndKeys:VALUE(KeyContent, self.msgDic),KeyContent,[mapArr objectAtIndex:[VALUE(KeyType, self.msgDic) integerValue]],KeyType,VALUE(KeyShowFrom, self.msgDic),KeyShowFrom,[NSNumber numberWithInteger:MyAppDataManager.selectedBubbleIndex],KeyBubbleID,VALUE(KeyThumbnail, self.msgDic),KeyThumbnail,nil];
                
                NSMutableDictionary *sendDic = [NSMutableDictionary dictionaryWithCapacity:5];
                [sendDic setValue:saysDic forKey:KeySays];
                [sendDic setValue:useridAndChatIDDic forKey:KeyChatid];
                [sendDic setValue:[self.chooseDic.allKeys componentsJoinedByString:@","] forKey:@"touid_list"];
                [sendDic setValue:[MyAppDataManager getLanguageSubmitToServer] forKey:@"lang"];
                
                //提交消息
                [AppComManager getBanBuData:BanBu_SendMessage_To_Server_V2 par:sendDic delegate:MyAppDataManager];
                
                //删除数组清空
                [self.chooseDic removeAllObjects];
            }
        });
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ( [tableView isEqual:self.searchDisplayController.searchResultsTableView] )
    {
        return self.searchResults.count;
    }
    else
    {
        return self.friendListArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    BanBu_FriendListCell *cell = (BanBu_FriendListCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(cell == nil)
    {
        cell = [[[BanBu_FriendListCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
    }
    NSDictionary * friendInfoDic = nil;
    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView])
    {
        NSString * pName = [self.searchResults objectAtIndex:indexPath.row];
        
        friendInfoDic = [self.pnameDic valueForKey:pName];
    }
    else
    {
        friendInfoDic = [self.friendListArray objectAtIndex:indexPath.row];
    }
    
    [cell setAvatar:[friendInfoDic valueForKey:KeyUface]];
    [cell setName:[friendInfoDic valueForKey:KeyPname]];
    
    NSDictionary * indexPathRow = [self.chooseDic valueForKey:[friendInfoDic valueForKey:KeyFromUid]];
    
    if (indexPathRow)
    {
        [cell setChecked:YES];
    }
    else
    {
        [cell setChecked:NO];
    }
    
    return cell;
}


- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleNone;
}

#pragma mark - Table view delegate
- (float)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 54;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if(self.tableView.editing || self.searchBl)
    {
        NSString * userid = @"";
        NSString * pName = @"";
        NSDictionary * userInfoDic = nil;
        if (self.searchBl)
        {
            pName = [self.searchResults objectAtIndex:indexPath.row];
            userid = [[self.pnameDic valueForKey:pName] valueForKey:KeyFromUid];
           
            userInfoDic = [self.pnameDic valueForKey:pName];
            
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:[self.pnameDic valueForKey:pName]];
            NSDictionary * linkToDic = [NSDictionary dictionaryWithObjectsAndKeys:@"toProfile",@"fc",userid,KeyFromUid, nil];
            
            NSString * jsonValue = [[CJSONSerializer serializer] serializeDictionary:linkToDic];
            jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            
            [dic setValue:jsonValue forKey:KeyLinkTo];
            
            self.visitCardInfoDic = dic;
        }
        else
        {
            pName = [[self.friendListArray objectAtIndex:indexPath.row] valueForKey:KeyPname];
            userid = [[self.friendListArray objectAtIndex:indexPath.row] valueForKey:KeyFromUid];
            userInfoDic = [self.friendListArray objectAtIndex:indexPath.row];
            
            NSMutableDictionary * dic = [NSMutableDictionary dictionaryWithDictionary:[self.friendListArray objectAtIndex:indexPath.row]];
            NSDictionary * linkToDic = [NSDictionary dictionaryWithObjectsAndKeys:@"toProfile",@"fc",userid,KeyFromUid, nil];
            
            NSString * jsonValue = [[CJSONSerializer serializer] serializeDictionary:linkToDic];
            jsonValue = [[jsonValue dataUsingEncoding:NSUTF8StringEncoding] base64EncodedString];
            
            [dic setValue:jsonValue forKey:@"linkto"];
            self.visitCardInfoDic = dic;
        }
        
        BOOL isChecked = YES ;
        
        if (![self.chooseDic valueForKey:userid])
        {
            isChecked = NO;
        }
        
        if(!isChecked)
        {
            if (self.chooseDic.count>4)
            {
                [TKLoadingView showTkloadingAddedTo:self.navigationController.view title:NSLocalizedString(@"theLargeNumber", nil) activityAnimated:NO duration:2];
                return;
            }
            [self.chooseDic setValue:userInfoDic forKey:userid];
        }
        else
        {
            [self.chooseDic removeObjectForKey:userid];
        }
        
        BanBu_FriendListCell *cell = (BanBu_FriendListCell *)[tableView cellForRowAtIndexPath:indexPath];
        
        [cell setChecked:!isChecked];
        
        [self.searchDisplayController setActive:NO animated:YES];
        
        if (self.isVisitingCard)
        {
            pName = [NSString stringWithFormat:@"%@%@",NSLocalizedString(@"sendVisitCard", nil),pName];

            UIAlertView * alert = [[UIAlertView alloc]initWithTitle:nil message:NSLocalizedString(pName, nil) delegate:self cancelButtonTitle:NSLocalizedString(@"cancelNotice", nil) otherButtonTitles:NSLocalizedString(@"confirmNotice", nil), nil];
            [alert show];
            [alert release];
        }
        else
        {
            self.visitCardInfoDic = nil;
        }
    }
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex)
    {
        case 0:
        {
            [self.chooseDic removeAllObjects];
            [self.tableView reloadData];
        }
            break;
        case 1:
        {
            if (self.isVisitingCard)
            {                
                NSDictionary * sendDic = [NSDictionary dictionaryWithObjectsAndKeys:self.visitCardInfoDic,KeyContent,[NSNumber numberWithInt:ChatCellTypeSpecialText],KeyType,@"visitCard",KeyShowFrom, nil];
                
                [[NSNotificationCenter defaultCenter]postNotificationName:kSendMsgAllTypeNotification object:sendDic];
                [self.navigationController popViewControllerAnimated:YES];
            }
        }
            break;
        default:
            break;
    }
}
-(void)viewWillAppear:(BOOL)animated
{
    [UIView setAnimationsEnabled:YES];
    [super viewWillAppear:animated];
}
#pragma mark - UISearchBarDelegate
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
    NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:@"SELF contains[cd] %@", searchText];
    
    self.searchResults = [self.pnameDic.allKeys filteredArrayUsingPredicate:resultPredicate];
}

#pragma mark -

-(void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
    self.searchBl = YES;
    UISearchBar *searchBar = self.searchDisplayController.searchBar;
    [searchBar setShowsCancelButton:YES animated:YES];
}

-(void)searchDisplayController:(UISearchDisplayController *)controller willHideSearchResultsTableView:(UITableView *)tableView
{
    self.searchBl = NO;
    [self.tableView reloadData];
}

-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString scope:[[self.searchDisplayController.searchBar scopeButtonTitles]  objectAtIndex:[self.searchDisplayController.searchBar selectedScopeButtonIndex]]];
    
    return(YES);
}


- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchScope:(NSInteger)searchOption
{
    [self filterContentForSearchText:[self.searchDisplayController.searchBar text] scope:[[self.searchDisplayController.searchBar scopeButtonTitles]objectAtIndex:searchOption]];
    
    return(YES);
}


-(void)dealloc
{
    MyAppDataManager.friendController = nil;
    
    [TKLoadingView dismissTkFromView:self.navigationController.view animated:YES afterShow:0];
    
    [_msgDic release];
    [_chooseButton release];
    [_friendListArray release];
    [_chooseDic release];
    
    [super dealloc];
}

@end
